module ApplicationHelper
  def label_for(object_name, attr, content=nil)
    object = instance_variable_get("@"+object_name.to_s);
    klass = (object) ? object.class : nil;
    unless klass
      begin; klass = object_name.classify.constantize;
      rescue NameError; end
    end
    if klass
      content = klass::AttributesNames[attr.to_sym] || content || attr.to_s;
      id = "#{object_name}_#{attr}";
    else
      content, id = attr, object_name;
    end
    content_tag("label", content, {:for => id});
    content_tag("label", {:for => id});
  end

  def button_to_action(name, action, options = {}, html_options = {}, *parameters_for_method_reference)
    options[:action] = action
    url = action.is_a?(String)? action : url_for(:action => options[:action], :id => options[:id], *parameters_for_method_reference)
    function = "location.pathname='#{url}'"
    if options.has_key? :method and options.has_key? :id then
      message = (options.has_key? :confirm)? "#{options[:confirm]}" : ""
      function = "if (confirm('#{(options.has_key? :confirm)? options[:confirm] : "Confirm?"}')) { " \
                 "var form = document.createElement('form'); form.style.display = 'none'; this.parentNode.appendChild(form); " \
                 "form.method = '#{options[:method].to_s.upcase}'; form.action = '#{url}'; form.submit(); } return false;"
    end
    button_to_function name, function, html_options
  end

  #Revisar o metodo para gerar automaticamente as funcoes javascript
  def button_to_action2(name, action, options = {}, html_options = nil, *parameters_for_method_reference)
    convert_options_to_javascript!(options)
    options[:action] = action
    url = options.is_a?(String) ? options : url_for(options, *parameters_for_method_reference)
    """
    <a href=\"#{url}\">#{name || action.to_s.capitalize}</a>
    <input type=\"button\" value=\"#{name || action.to_s.capitalize}\"/>
    """
#   if html_options
#     html_options = html_options.stringify_keys
#   #  convert_options_to_javascript!(html_options)
#     tag_options = tag_options(html_options)
#   else
#     tag_options = nil
#   end

#   url      = options.is_a?(String) ? options.to_s : url_for(action, options, *parameters_for_method_reference)
#   y tag_options
#   # tag_options[:onclick] => url
#   button = tag :input, tag_options
#   #"<input type=\"button\" value=\"#{name || url}\" \"#{url}\"#{tag_options}/>"
#   "<a href=\"#{url}\"#{tag_options}>#{name || action.to_s.capitalize}</a>"
#    "<input type=\"button\" value=\"#{name || url}\"#{tag_options}/>"
  end
end

